package nio.client;

import sun.util.resources.cldr.bn.LocaleNames_bn_IN;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * Created by ASUS on 2017/10/19.
 */
public class NioClient {

    private static String USER_EXIST="系统提示:该昵称已经存在,请换一个昵称";
    private static String USER_CONTENT_SPILIT="#@#";

    private Selector selector;//对应的选择器
    private static InetSocketAddress inetSocketAddress=new InetSocketAddress("localhost",8080);
    private  SocketChannel client;
    private String nickName="";//昵称
    Charset charset=Charset.forName("UTF-8");

    public NioClient() throws IOException {
        //先把路修好
        client=SocketChannel.open(inetSocketAddress);
        client.configureBlocking(false);//设置非阻塞模式

        //开门接客
        selector=Selector.open();
        client.register(selector, SelectionKey.OP_READ);
    }

    public static void main(String args[]) {
        try {
            new NioClient().session();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 进行绘话
     */
    public void session(){
        //开辟一个新的线程从服务器读取数据
       new Reader().start();
       //开辟一个新线程从服务端写数据
       new Writer().start();
    }
    /**
     * 写的线程
     */
    private class Writer extends Thread{
        @Override
        public void run() {
            try {
                Scanner scan=new Scanner(System.in);
                while (scan.hasNextLine()) {
                    String line=scan.nextLine();
                    if("".equals(line)) continue;
                    if("".equals(nickName)){
                       nickName=line;
                       line=nickName+USER_CONTENT_SPILIT;
                    }else{
                        line=nickName+USER_CONTENT_SPILIT+line;
                    }
                    client.write(charset.encode(line));
                }
                scan.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 读的提示
     */
    private class Reader extends Thread{
        @Override
        public void run() {
            try {
                while (true) {
                    int readyChannels=selector.select();
                    if(readyChannels==0) continue;
                    Set<SelectionKey> selectionKeySet=selector.selectedKeys();
                    Iterator<SelectionKey> iterable=selectionKeySet.iterator();
                    while (iterable.hasNext()) {
                        process(iterable.next());
                        iterable.remove();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /**
         * 进行处理
         * @param key
         */
        private void process(SelectionKey key) throws IOException{
            System.out.println("NioClient key:"+key);
            if (key.isReadable()) {
                //是可读的
                SocketChannel socketChannel=(SocketChannel) key.channel();
                //缓冲区
                ByteBuffer byteBuffer= ByteBuffer.allocate(1024);
                String content="";
                while (socketChannel.read(byteBuffer)>0) {
                    byteBuffer.flip();//重置位置 便于写
                    content+=charset.decode(byteBuffer);
                }
                //如果系统通知 昵称已经存在
                if(content.equals(USER_EXIST)){
                    nickName="";
                }
                System.out.println("..."+content);
            }
        }
    }
}
